<script setup lang="ts">
import dayjs from 'dayjs'
import toObject from 'dayjs/plugin/toObject'
import { ref, watch, nextTick } from 'vue'
import { base64ToBlob, mimeTypes, checkBlobUrlValidity } from '../../utils/blob'

dayjs.extend(toObject)

const emit = defineEmits(['remove'])

const props = defineProps({
    active: {
        type: Object,
        default: () => ({} as ChatMenu)
    },
    avatar: {
        type: String,
        default: ''
    },
    webviewHome: {
        type: String,
        default: 'https://www.bing.com'
    }
})

const chatCount = ref(0)

watch(() => props.active, () => {
    chatCount.value = props.active.chats.length || 0
}, { deep: true, immediate: true })

watch(chatCount, async () => {
    let chats = props.active.chats || [], effectiveBlob = false
    for (let i = 0; i < chats.length; i++) {
        if (chats[i].type !== 1) continue
        if (!effectiveBlob) effectiveBlob = await checkBlobUrlValidity(chats[i].image)
        if (chats[i].image && effectiveBlob) continue
        let file = await window.ipcRenderer.invoke('load-local-file', chats[i].text)
        let blob = base64ToBlob(file.base64, mimeTypes(file.ext))
        chats[i].image = URL.createObjectURL(blob)
    }

    await nextTick()

    const element = document.body.querySelector('.chat-box .el-scrollbar__wrap') as HTMLElement
    if (element) {
        element.scrollTop = element.scrollHeight
    }
}, { immediate: true })

const handleTime = (time: string) => {
    if (!dayjs().isSame(time, 'year')) {
        return dayjs(time).format('YYYY/MM/DD')
    }
    if (!dayjs().isSame(time, 'day')) {
        if (dayjs().diff(time, 'hour') < 48) {
            return '昨天 ' + dayjs(time).format('HH:mm')
        }
        return dayjs(time).format('MM/DD')
    }
    return dayjs(time).format('HH:mm')
}

const resizeObserver = new ResizeObserver(entries => {
    entries.forEach(entry => {
        const webview = document.querySelector('webview') as any
        if (webview) {
            webview.style.width = `${entry.contentRect.width}px`
        }
    })
})

const handleFish = (chat: Chat) => {
    // 移除其他 webview 元素
    document.body.querySelectorAll('webview').forEach(el => el.remove())

    const image = document.querySelector(`.image[chat-id="${chat.id}"]`) as HTMLImageElement
    const webview = document.createElement('webview') as HTMLWebViewElement
    webview.id = 'website'
    webview.src = props.webviewHome
    webview.allowpopups = true
    image.append(webview)
    resizeObserver.observe(image)
    webview.addEventListener('did-finish-load', () => {
        // 插入js
        webview.executeJavaScript(window.electronIpc.insertJs, true)
        // 运行特殊网站脚本
        webview.executeJavaScript('setTimeout(handleSpecialWebsite, 1500)', true)
    })
}

const handleRemove = (chat: Chat) => {
    const chats = (props.active.chats || []) as Chat[],
        index = chats.findIndex(item => item.id === chat.id)
    chats.splice(index, 1)
}
</script>
<template>
    <el-scrollbar class="chat-box">
        <div class="box" v-for="chat in active.chats" :key="chat.id">
            <p v-if="chat.isLongTime" class="time">{{ handleTime(chat.time) }}</p>
            <el-row :class="{ reverse: chat.position === 'right' }" :chat-id="chat.id">
                <el-dropdown popper-class="wechat-dropdown" trigger="contextmenu">
                    <el-avatar shape="square" :size="35"
                        :fit="chat.position === 'right' ? props.avatar : props.active.imageBlobUrl"
                        :src="chat.position === 'right' ? props.avatar : props.active.imageBlobUrl" />
                    <template #dropdown>
                        <el-dropdown-menu>
                            <el-dropdown-item :disabled="chat.type !== 1"
                                @click="handleFish(chat)">摸鱼</el-dropdown-item>
                            <el-dropdown-item class="danger" divided @click="handleRemove(chat)">
                                <el-text type="danger">删除</el-text>
                            </el-dropdown-item>
                        </el-dropdown-menu>
                    </template>
                </el-dropdown>
                <div class="info">
                    <p class="nickname">{{ chat.position === 'left' ? props.active.title : '' }}</p>
                    <div class="text" v-if="chat.type === 0">
                        <p>{{ chat.text }}</p>
                    </div>
                    <div class="image" :chat-id="chat.id" v-if="chat.type === 1">
                        <img :src="chat.image" />
                    </div>
                </div>
            </el-row>
        </div>
    </el-scrollbar>
</template>
<style lang="scss" scoped>
.chat-box {
    :deep(#website) {
        position: absolute;
        top: 0;
        height: 100%;
        background-color: #000000;
    }

    .box {
        padding: 15px 18px;

        &:last-of-type {
            padding-bottom: 20px;
        }

        .webscreen {
            position: absolute !important;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0 !important;
            margin: 0 !important;
            padding: 0;
            z-index: 100;
            width: 100%;
        }

        .time {
            color: #9e9e9e;
            font-size: 12px;
            text-align: center;
            padding-bottom: 15px;
        }

        .reverse {
            flex-direction: row-reverse;

            .info {
                .nickname {
                    display: none;
                }

                .text {
                    margin-top: 0px;
                    background-color: #95ec69;
                }

                .image {
                    margin-top: 0px;
                }
            }
        }

        .info {
            margin: 0 15px;
            max-width: 60%;

            &:has(.webscreen) {
                max-width: unset;

                .image {
                    border-radius: unset;
                    margin-top: 0px;
                }
            }

            p {
                line-height: 12px;
            }

            .nickname {
                font-size: 12px;
                color: #9e9e9e;
            }

            .text {
                padding: 8px 12px;
                border-radius: 4px;
                margin-top: 8px;
                display: inline-block;

                // white-space: pre;
                overflow-wrap: break-word;
                word-break: break-all;

                background-color: #ffffff;

                p {
                    line-height: 20px;
                }
            }

            .image {
                position: relative;
                overflow: hidden;
                border-radius: 4px;
                margin-top: 8px;
                background-color: #000000;

                img {
                    width: 100%;
                    max-height: 410px;
                    display: block;
                }
            }
        }
    }
}
</style>